/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.tms.web;

import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.jeeplus.modules.infor.entity.Goods;
import com.jeeplus.modules.infor.entity.Project;
import com.jeeplus.modules.infor.service.GoodsService;
import com.jeeplus.modules.infor.service.ProjectService;
import com.jeeplus.modules.infor.service.TakeAddressService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.tms.entity.*;
import com.jeeplus.modules.tms.mapper.InformationsMapper;
import com.jeeplus.modules.tms.mapper.MaterialInformationsMapper;
import com.jeeplus.modules.tms.mapper.TmsMaterialsInformationMapper;
import com.jeeplus.modules.tms.service.PlanningService;
import com.jeeplus.modules.tms.service.TmsWaybillService;
import com.jeeplus.modules.wms.entity.MaterialParticulars;
import com.jeeplus.modules.wms.util.CopyUtil;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.tms.service.TransportPlanningService;

/**
 * 运输计划Controller
 * @author 李超辉
 * @version 2017-12-04
 */
@Controller
@RequestMapping(value = "${adminPath}/tms/transportPlanning")
public class TransportPlanningController extends BaseController {

	@Autowired
	private TransportPlanningService transportPlanningService;
	@Autowired
	private JdbcTemplate jdbc;
	@Autowired
	private TmsWaybillService service;
	@Autowired
	private TakeAddressService takeAddressService;
	@Autowired
	private TmsMaterialsInformationMapper m;
	@Autowired
	private PlanningService planningService;
	@Autowired
	private MaterialInformationsMapper materialInformationsMapper;
	@Autowired
	private InformationsMapper informationsMapper;
	@Autowired
	private GoodsService goodsService;
	@ModelAttribute
	public TransportPlanning get(@RequestParam(required=false) String id) {
		TransportPlanning entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = transportPlanningService.get(id);
		}
		if (entity == null){
			entity = new TransportPlanning();
		}
		return entity;
	}
	
	/**
	 * 委托单列表页面
	 */
	@RequiresPermissions("tms:transportPlanning:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/tms/transportPlanningList";
	}

	
		/**
	 * 委托单列表数据
	 */
	@ResponseBody
	@RequiresPermissions("tms:transportPlanning:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(TransportPlanning transportPlanning, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro= UserUtils.getUseroffice();
		if(!pro.equals("总部")){transportPlanning.setProjectName(pro);}
		Page<TransportPlanning> page = transportPlanningService.findPage(new Page<TransportPlanning>(request, response), transportPlanning);
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑运输计划表单页面
	 */
	@RequiresPermissions(value={"tms:transportPlanning:view","tms:transportPlanning:add","tms:transportPlanning:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(TransportPlanning transportPlanning, Model model) {
		if(transportPlanning.getId()!=null){
        List<Map<String,Object>> list=jdbc.queryForList("SELECT type ,sum(gross) as gross,SUM(weight)as weight, SUM(volume)  as volume,depot FROM `tms_material_informations` where transport_planning='"+transportPlanning.getId()+"' GROUP BY type,depot;");
			NumberFormat nf = NumberFormat.getInstance();
			for(Map<String,Object> m:list){
				m.put("weight",nf.format(Double.parseDouble(m.get("weight")+"")));
				m.put("volume",nf.format(Double.parseDouble(m.get("volume")+"")));
				m.put("depot",m.get("depot")+"");
			}
        model.addAttribute("list", list);
			TmsWaybill bill=new TmsWaybill();
			bill.setEntrustNumber(transportPlanning.getEntrustNumber());
			List<TmsWaybill> lis=service.findList(bill);
			for(TmsWaybill t:lis){

				t.setTmsMaterialsInformationList(m.findList(new TmsMaterialsInformation(t)));
			}
			model.addAttribute("bills",lis);

		}else{
			transportPlanning.setStatus("已创建");
			transportPlanning.setPlanStatus("未计划");
		}
		model.addAttribute("transportPlanning", transportPlanning);
		return "modules/tms/transportPlanningForm";
	}

	@ResponseBody
	@RequestMapping(value = "cd")
	public  String cd(TransportPlanning t) throws ParseException {
		NumberFormat nf = NumberFormat.getInstance();
		t.setPlanStatus("计划完成");
		t.setWeight(Double.parseDouble (nf.format(t.getWeight()-t.getWf()).replaceAll(",","")));
		Planning planning=planningService.get(t.getPid());
		Planning pp=new Planning();
		pp= (Planning) CopyUtil.Copy(pp,planning,false);
		planning.setWeight(t.getWeight());
		pp.setStatus("已创建");
		pp.setEntrustNumber(planning.getEntrustNumber()+"-01");
		pp.setShipmentNumbers(planning.getShipmentNumbers()+"-01");
		pp.setWeight(t.getWf());
		planningService.save(pp);
		t.setWf(0.0);
		List<Informations> l=planning.getInformationsList();

		List<MaterialInformations> list=t.getMaterialInformationsList();
		for(MaterialInformations m:list){
              if(m.getVehicleQuantity().equals("0")){


				  for(Informations in:l){
				  	if(in.getCoding().equals(m.getCoding())&&in.getDepot().getStore().equals(m.getDepot())){
						Informations i=new Informations();
						i= (Informations) CopyUtil.Copy(i,in,false);
						i.setPlanning(pp);
						i.setId(UUID.randomUUID().toString().replaceAll("-",""));
						informationsMapper.insert(i);
				  		informationsMapper.delete(in);
					}
				  }
				  materialInformationsMapper.delete(m);
			  }else if(m.getRemain().equals("0")){

			  }else{
				  Goods g=goodsService.get(m.getGoods());
				  String w=g.getGrossWeight();
				  String v=g.getVolume();
				  String sl=m.getVehicleQuantity();
				  String sy=m.getRemain();
				  double weig=Double.parseDouble(w)*Double.parseDouble(sl);
				  double voi=Double.parseDouble(v)*Double.parseDouble(sl);
				  double sweig=Double.parseDouble(w)*Double.parseDouble(sy);
				  double svoi=Double.parseDouble(v)*Double.parseDouble(sy);


				  for(Informations in:l){
					  if(in.getCoding().equals(m.getCoding())&&in.getDepot().getStore().equals(m.getDepot())){
						 in.setGross(m.getVehicleQuantity());
						 in.setWeight(nf.format(weig).replaceAll(",",""));
						  in.setVolume(nf.format(voi).replaceAll(",",""));
						  informationsMapper.update(in);
						  Informations i=new Informations();
						  i= (Informations) CopyUtil.Copy(i,in,false);
						  i.setGross(m.getRemain());
						  i.setPlanning(pp);
						  i.setWeight(nf.format(sweig).replaceAll(",",""));
						  i.setVolume(nf.format(svoi).replaceAll(",",""));
						  i.setId(UUID.randomUUID().toString().replaceAll("-",""));
						  informationsMapper.insert(i);
					  }
				  }

			  	m.setRemain("0");
			  	m.setGross(m.getVehicleQuantity());
				  m.setWeight(nf.format(weig).replaceAll(",",""));
				 m.setVolume(nf.format(voi).replaceAll(",",""));
			   materialInformationsMapper.update(m);
			  }
		}
		transportPlanningService.save(t);
		TmsWaybill tb=new TmsWaybill();
		tb.setPid(planning.getId());
		List<TmsWaybill> bills=service.findList(tb);
		boolean bol=true;
		for(TmsWaybill bill:bills){
			if(!bill.getHtzt().equals("1")){
				bol=false;
				break;
			}
		}
		if(bol){
			planning.setJftj("满足");
		}
		planningService.save(planning);
		return "";
	}

	/**
	 * 保存委托单
	 */
	@ResponseBody
	@RequiresPermissions(value={"tms:transportPlanning:add","tms:transportPlanning:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(TransportPlanning transportPlanning, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, transportPlanning)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		//新增或编辑表单保存
		transportPlanningService.save(transportPlanning);//保存
		j.setSuccess(true);
		j.setMsg("保存委托单成功");
		return j;
	}
	
	/**
	 * 删除委托单
	 */
	@ResponseBody
	@RequiresPermissions("tms:transportPlanning:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(TransportPlanning transportPlanning, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		transportPlanningService.delete(transportPlanning);
		j.setMsg("删除委托单成功");
		return j;
	}
	
	/**
	 * 批量删除委托单
	 */
	@ResponseBody
	@RequiresPermissions("tms:transportPlanning:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			transportPlanningService.delete(transportPlanningService.get(id));
		}
		j.setMsg("删除委托单成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("tms:transportPlanning:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(TransportPlanning transportPlanning, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "委托单"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<TransportPlanning> page = transportPlanningService.findPage(new Page<TransportPlanning>(request, response, -1), transportPlanning);
    		new ExportExcel("委托单", TransportPlanning.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出委托单记录失败！失败信息："+e.getMessage());
		}
			return j;
    }
    
    @ResponseBody
    @RequestMapping(value = "detail")
	public TransportPlanning detail(String id) {
		return transportPlanningService.get(id);
	}
	

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("tms:transportPlanning:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<TransportPlanning> list = ei.getDataList(TransportPlanning.class);
			for (TransportPlanning transportPlanning : list){
				try{
					transportPlanningService.save(transportPlanning);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条委托单记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条委托单记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入委托单失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/tms/transportPlanning/?repage";
    }
	
	/**
	 * 下载导入委托单数据模板
	 */
	@RequiresPermissions("tms:transportPlanning:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "委托单数据导入模板.xlsx";
    		List<TransportPlanning> list = Lists.newArrayList(); 
    		new ExportExcel("委托单数据", TransportPlanning.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/tms/transportPlanning/?repage";
    }
	

}